package com.yami.shop.seckill.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.event.SubmitSeckillOrderEvent;
import com.yami.shop.bean.model.Order;
import com.yami.shop.seckill.common.model.Seckill;
import com.yami.shop.seckill.common.model.SeckillOrder;
import com.yami.shop.seckill.common.service.SeckillOrderService;
import com.yami.shop.seckill.common.service.SeckillService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 获取订单相关信息
 * @author yami
 */
@Component("seckillGetSeckillOrderInofListener")
@AllArgsConstructor
public class GetSeckillOrderInofListener {

    private final SeckillOrderService seckillOrderService;
    private final SeckillService seckillService;

    @EventListener(SubmitSeckillOrderEvent.class)
    public void seckillGetSeckillOrderInofListener(SubmitSeckillOrderEvent event) {
        Order order = event.getOrder();
        event.setMaxCancelTime(0);
        if (Objects.isNull(order)) {
            return;
        }
        String orderNumber = order.getOrderNumber();
        List<SeckillOrder> list = seckillOrderService.list(new LambdaQueryWrapper<SeckillOrder>().eq(SeckillOrder::getOrderNumber, orderNumber));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        SeckillOrder seckillOrder = list.get(0);
        Seckill seckill = seckillService.getSeckillById(seckillOrder.getSeckillId());
        if (Objects.isNull(seckill)) {
            return;
        }
        event.setMaxCancelTime(seckill.getMaxCancelTime());
    }

}
